import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class benchmark_rede_externa {
    private String cmdLine;

    public benchmark_rede_externa() {
    	this.cmdLine = "iperf -c 200.129.43.221 -f k";
	}
    
    public benchmark_rede_externa(String host) {
    	this.cmdLine = "iperf -c "+host+" -f m";
    }

    public void iperf() {
        try {
            String cmdOutput = cmdExec(cmdLine);
            System.out.println(cmdOutput);
            
            Pattern pattern = Pattern.compile("MBytes (.*?) Mbits/sec");
            Matcher matcher = pattern.matcher(cmdOutput);
            matcher.find();
            
            double bandwidth = Double.parseDouble(matcher.group(1).trim());
            FileWriter result_rede_externa = new FileWriter("benchmark_rede_externa_result.txt");
    		result_rede_externa.write(""+bandwidth+"\n");
    		result_rede_externa.close();

        } catch (Exception ex) {
            System.err.println("ERROR - invalid response from system ping");
            ex.printStackTrace();
        }
    }
    // run a system command and return output
    public static String cmdExec(String cmdLine) {
        String line;
        String output = "";
        try {
            Process p = Runtime.getRuntime().exec(cmdLine);
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                output += (line);
            }
            input.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return output;
    }	
    public static void main(String[] args) {
    	benchmark_rede_externa p = null;
    	for (String s: args) {
    		p = new benchmark_rede_externa(s);
    	}
        p.iperf();
    }
}
